/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.iprange.info;

import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Iprangeuser;
import cn.net.greenet.db.bean.IprangeuserRange;
import com.ambimmort.umessage.util.IPv4Util;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author ShiYun,2014/11/30
 */
public class IpRangeService {

    public static void save(String policy) {
        System.out.println("==============IpRangeService Save===================");
        JSONObject one = JSONObject.fromObject(policy);
        String username = one.getString("UserName");
        System.out.println("user:" + username);
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        session.clear();
        Query query = session.createQuery("from Iprangeuser where name = :name").setParameter("name", username);
        List beans = query.list();
        System.out.println("size:" + beans.size());
        Transaction tx = session.beginTransaction();
        try {
            Iprangeuser iprange = null;
            if (beans.isEmpty()) {
                iprange = new Iprangeuser();
                iprange.setName(username);
                session.save(iprange);
                session.flush();
                query = session.createQuery("from Iprangeuser where name = :name").setParameter("name", username);
                beans = query.list();
                System.out.println("size:" + beans.size());
            }
            iprange = (Iprangeuser) beans.get(0);
            query = session.createQuery("delete IprangeuserRange where iprangeuser = :bean").setParameter("bean", iprange);
            int ext = query.executeUpdate();
            System.out.println("line:" + ext);
            String IP_Segments = one.getString("IP_Segments");
            JSONArray arr = JSONObject.fromObject(IP_Segments).getJSONArray("IP_Segment");
            System.out.println("arr size:" + arr.size());

            for (Object arr1 : arr) {
                IprangeuserRange iprangeuser = new IprangeuserRange();
                JSONObject ips = JSONObject.fromObject(arr1);
                JSONObject ip = ips.getJSONObject("UserIP");
                int prefix = ips.getInt("UserIP_Prefix");
                String iptype = ip.getString("IPType");
                String ipAddress = ip.getString("IPv4Address");
                System.out.println("ipType:" + iptype + ",ip:" + ipAddress + ",prefix:" + prefix);
                //IPv4:0  IPv6:1
                iprangeuser.setPrefix(prefix);
                if (iptype.equals("IPv4")) {
                    iprangeuser.setType(new Byte("0"));
                    iprangeuser.setIpv4(IPv4Util.ipToInt(ipAddress));
                } else {
                    iprangeuser.setType(new Byte("1"));
                    iprangeuser.setIpv6(ipAddress);
                }
                iprangeuser.setIprangeuser(iprange);
                iprange.getIprangeuserRanges().add(iprangeuser);
                session.saveOrUpdate(iprangeuser);
            }
            session.saveOrUpdate(iprange);
            tx.commit();
        } catch (HibernateException | NumberFormatException e) {
            tx.rollback();
        } finally {
            session.close();
        }
        System.out.println("==============IpRangeService Save===================");
    }

    public static boolean isCotain(Set<IprangeuserRange> list, IprangeuserRange one) {
        for (IprangeuserRange list1 : list) {
            if (Objects.equals(list1.getIpv4(), one.getIpv4()) && Objects.equals(list1.getPrefix(), one.getPrefix()) && Objects.equals(list1.getType(), one.getType())) {
                return true;
            }
        }
        return false;
    }

    public static IprangeuserRange equalIP(Set<IprangeuserRange> list, IprangeuserRange one) {
        for (IprangeuserRange list1 : list) {
            if (Objects.equals(list1.getIpv4(), one.getIpv4())) {
                return list1;
            }
        }
        return null;
    }

    public static void main(String[] args) {
//        SessionFactory sf = HibernateUtil.getSessionFactory();
//        Session session = sf.openSession();
//        session.clear();
//        String username = "test";
//        Query query = session.createQuery("from Iprangeuser where name = :name").setParameter("name", username);
//        List beans = query.list();
//        System.out.println("size:" + beans.size());
//        session.close();
//        sf.close();
        String policy = "{\"IP_Segments\":{\"IP_Segment\":[{\"UserIP_Prefix\":\"25\",\"UserIP\":{\"IPType\":\"IPv4\",\"IPv4Address\":\"10.10.2.33\"}},{\"UserIP_Prefix\":\"2\",\"UserIP\":{\"IPType\":\"IPv4\",\"IPv4Address\":\"10.10.2.25\"}}]},\"Bind_Action\":\"1\",\"UserName\":\"shiyun\"}";
        save(policy);
    }
}
